package winOrDie.Game;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;

import rice.environment.Environment;
import rice.pastry.NodeIdFactory;
import rice.pastry.PastryNode;
import rice.pastry.PastryNodeFactory;
import rice.pastry.socket.SocketPastryNodeFactory;
import rice.pastry.standard.RandomNodeIdFactory;

import winOrDie.Application.WoD_Application_Data;
import winOrDie.GameEngine.P2P.WoD_P2P_Peer;
import winOrDie.GameEngine.P2P.WoD_P2P_Peer_Event;
import winOrDie.GameEngine.P2P.WoD_P2P_Peer_Listener;
import winOrDie.GameEngine.RT.mp.WoD_MapBoard_Event;
import winOrDie.GameEngine.RT.mp.WoD_MapBoard_Listener;
import winOrDie.Net.WoD_Net_Protocol_ASCII;
import winOrDie.Net.WoD_Net_Protocol_Manager;
import winOrDie.Net.Client.WoD_Peer;
import winOrDie.Net.Client.WoD_Peers_List;
import winOrDie.Net.Http.httpmsg.WoD_HttpMessage;
import winOrDie.Net.Http.httpmsg.WoD_InfoPartidasActuales;
import winOrDie.Net.P2P.WoD_P2P_Control_Channel_Event;
import winOrDie.Net.P2P.WoD_P2P_Control_Channel_Listener;
import winOrDie.Net.P2P.WoD_ScribeContent;
import winOrDie.Net.Server.WoD_Server_Client;
import winOrDie.Sound.Voice.WoD_Voice;
import winOrDie.Sound.Voice.WoD_Voice_Time;
import winOrDie.graphicsInterface.GameRoom.Composite_Chat_Event;
import winOrDie.graphicsInterface.GameRoom.Composite_Chat_Listener;
import winOrDie.graphicsInterface.GameRoom.Composite_GameRoom;
import winOrDie.graphicsInterface.GameRoom.Composite_Maps_Event;
import winOrDie.graphicsInterface.GameRoom.Composite_Maps_Listener;
import winOrDie.graphicsInterface.GameRoom.Composite_Options_Event;
import winOrDie.graphicsInterface.GameRoom.Composite_Options_Listener;
import winOrDie.graphicsInterface.GameRoom.Composite_Rols_Event;
import winOrDie.graphicsInterface.GameRoom.Composite_Rols_Listener;
import winOrDie.graphicsInterface.RT.Shell_RT_Game;

public class WoD_Game_Manager 
implements  
Composite_Chat_Listener, 
WoD_P2P_Control_Channel_Listener, 
Composite_Options_Listener,
WoD_P2P_Peer_Listener,
Composite_Rols_Listener,
Composite_Maps_Listener
{
	
	private WoD_Application_Data woDApplicationData = null;
	
	private PastryNode node = null;
	private WoD_P2P_Peer woDP2PPeer = null;
	
	public WoD_P2P_Peer getWoDP2PPeer() {
		return woDP2PPeer;
	}
	
	private Composite_GameRoom compositeGameRoom = null;
	
	private WoD_Net_Protocol_Manager woDNetProtocolManager = null;
	
	Shell_RT_Game shellRTGame = null;
	
		
	private Vector<WoD_Game_Manager_Listener> listeners = null;

	private WoD_Voice wod_Voice = null;;
	
	public synchronized void add_WoD_Game_Manager_Listener(WoD_Game_Manager_Listener listener)
	{
		listeners.add(listener);
	}
	
	public synchronized void remove_WoD_Game_Manager_Listener(WoD_Game_Manager_Listener listener)
	{
		listeners.remove(listener);
	}
	
	protected void notify_WoD_Game_Manager_Change(WoD_Game_Manager_Event event)
	{
		for (WoD_Game_Manager_Listener listener : listeners) {
			listener.on_WoD_Game_Manager_Change(event);
		}
	}
	
	public WoD_Game_Manager(
			WoD_Application_Data woDApplicationData,
			Composite_GameRoom compositeGameRoom
			) throws Exception
	{

		this.woDApplicationData = woDApplicationData;
		this.compositeGameRoom = compositeGameRoom;
		
		woDNetProtocolManager = new WoD_Net_Protocol_Manager();
		
		woDApplicationData.getWoDGame().setMap_Name("inferno.xml");
		
		initialize();
	}

	
	private void initialize() throws Exception
	{
		
		// Loads pastry configurations
		Environment env = new Environment();

		// disable the UPnP setting (in case you are testing this on a NATted LAN)
		env.getParameters().setString("nat_search_policy","never");
		
		/**
		 * Server BootAddress 
		 */
		InetSocketAddress bootaddress = new InetSocketAddress(
				woDApplicationData.getWoDGame().getServerHost(), 
				woDApplicationData.getWoDGame().getServer_port());
		
		
		
		// Generate the NodeIds Randomly
		NodeIdFactory nidFactory = new RandomNodeIdFactory(env);

		// construct the PastryNodeFactory, this is how we use rice.pastry.socket
		PastryNodeFactory factory = new SocketPastryNodeFactory(
				nidFactory, 
				woDApplicationData.getWoDConfiguration().getControl_Port(), 
				env);
		
		
		node = factory.newNode();
		
		
		
//		woDClient = new WoD_Client(node);
	
		
		woDP2PPeer = new WoD_P2P_Peer(node, woDApplicationData);
		woDP2PPeer.add_WoD_P2P_Peer_Listener(this);

		/**
		 * Initialize Pastry node
		 */
		node.boot(bootaddress);
		// the node may require sending several messages to fully boot into the ring
		synchronized(node) {
			while(!node.isReady() && !node.joinFailed()) {
				// delay so we don't busy-wait
				node.wait(500);

				// abort if can't join
				if (node.joinFailed()) {
					throw new IOException("Could not join the FreePastry ring.  Reason:"+node.joinFailedReason());
				}
			}       
		}
		
		compositeGameRoom.get_Composite_Chat().add_Composite_Chat_Listener(this);
		compositeGameRoom.get_Composite_Options().add_Composite_Options_Listener(this);
		compositeGameRoom.get_Composite_Rols().add_Composite_Rols_Listener(this);
		compositeGameRoom.create_List_Maps().add_Composite_Maps_Listener(this);
		
		woDApplicationData.getWoDConfiguration().setHost_Direction(
				InetAddress.getLocalHost().getHostAddress());
		
		
		
//		woDClient.getWoDClientControlChannel().add_WoD_Client_ControlChannel_Listener(this);

		
		woDP2PPeer.getWoDP2PControlChannel().add_WoD_P2P_Control_Channel_Listener(this);
//		woDClient.getWoDClientControlChannel().start_WoD_Client_ControlChannel();
		woDP2PPeer.getWoDP2PControlChannel().start_WoD_P2P_Control_Channel();

		
		Runnable runnable_Join_Game = new Runnable() {
			
			@Override
			public void run() {
				try {
					woDP2PPeer.send_Join_Game();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		};
		compositeGameRoom.getDisplay().timerExec(100, runnable_Join_Game);
		
		//Thread.currentThread().sleep(3000);
		
		
		Runnable runnable_Check_Root = new Runnable() {
			
			@Override
			public void run() {
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().check_Root();
				
			}
		};
		
		compositeGameRoom.getDisplay().timerExec(3000, runnable_Check_Root);
		
		
		
	}
	
	@Override
	public void on_WoD_P2P_Control_Channel_Change(final WoD_P2P_Control_Channel_Event event) {
		
		WoD_ScribeContent woDScribeContent = null;
		switch (event.getEvent_Type()) {
		case WoD_P2P_Control_Channel_Event.Event_Types.CHAT:
			
						
			compositeGameRoom.getDisplay().asyncExec(new Runnable() {
				public void run() {
					
					String message_total2 = event.getData().toString();
				
					compositeGameRoom.get_Composite_Chat().get_Text_Output().append(message_total2 + "\n");
				}
			});
			break;
			
		case WoD_P2P_Control_Channel_Event.Event_Types.GAME_ID:
			String message_total = event.getData().toString();
			String GameID = message_total.substring(0, message_total.indexOf("/"));
			String GameTitle = message_total.substring(message_total.indexOf("/")+1, message_total.length() );

			woDApplicationData.getWoDGame().setID_Game(Long.parseLong(GameID));
			woDApplicationData.getWoDGame().setGame_Title(GameTitle);
			break;
		
		case WoD_P2P_Control_Channel_Event.Event_Types.CLIENT_JOIN_GAME_KO:
			
			manage_CLIENT_JOIN_GAME_KO(event);
			break;
			
		case WoD_P2P_Control_Channel_Event.Event_Types.CLIENT_JOIN_GAME_OK:
			
			woDScribeContent = (WoD_ScribeContent)event.getData();
			//manage_CLIENT_SELECT_SIDE_OK(event);
			System.out.println("Join Game OK");			
			break;			
			
		case WoD_P2P_Control_Channel_Event.Event_Types.P2P_I_AM_ROOT:
			System.out.println("I am Root");
			break;
		
		
		case WoD_P2P_Control_Channel_Event.Event_Types.CLIENT_SELECT_SIDE_KO:
			manage_CLIENT_SELECT_SIDE_KO(event);
			break;			
			
		case WoD_P2P_Control_Channel_Event.Event_Types.CLIENT_SELECT_SIDE_OK:
			manage_CLIENT_SELECT_SIDE_OK(event);
			break;
			
		case WoD_P2P_Control_Channel_Event.Event_Types.CLIENT_SELECT_ROL_OK:
			manage_CLIENT_SELECT_ROLE_OK(event);
			break;			
			
		case WoD_P2P_Control_Channel_Event.Event_Types.SERVER_FORCE_START:
			System.out.println("Root is going to start the game");	
			break;


		case WoD_P2P_Control_Channel_Event.Event_Types.SERVER_COUNT_DOWN:
			System.out.println("COUNT DOWN TO START GAME");
			
			woDScribeContent = (WoD_ScribeContent)event.getData();
			
			
			try {
				long ts_Start = woDNetProtocolManager.parse_COUNT_DOWN(woDScribeContent.getMessage());
				
				
				
				Composite_Options_Event optionsEvent = new Composite_Options_Event(this);
				optionsEvent.setEventType(Composite_Options_Event.Event_Types.GAME_RT_START);
				optionsEvent.setData(ts_Start);
				compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
//			mapGenerator = new MapGenerator();
//			mapGenerator.execute();
//			woDScribeContent = (WoD_ScribeContent)event.getData();
//			
//			long ts_Start_Game;
//			try {
//				ts_Start_Game = woDNetProtocolManager.parse_COUNT_DOWN(woDScribeContent.getMessage());
//				shellRTGame = new Shell_RT_Game(
//						woDP2PPeer.get_My_WoD_Peer(),
//						woDP2PPeer.getWoDClientRT(),
//						woDP2PPeer.getWoDClientPeersList(), 
//						ts_Start_Game);
//				
//				woDP2PPeer.getWoDClientRT().add_WoD_Client_RT_Listener(shellRTGame.getCompositeRTGame().get_Map_Board());
//				shellRTGame.getCompositeRTGame().get_Map_Board().add_WoD_MapBoard_Listener(woDP2PPeer);
//				shellRTGame.execute();
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		
			
			

			
			
			
			break;
			
			
		default:
			break;
		}
		
	}
	
	@Override
	public void on_Composite_Options_Changed(Composite_Options_Event event) {
		switch (event.getEventType()) {
		
		case Composite_Options_Event.Event_Types.TEAM_CAPTAIN:
			try {
				byte[] message_To_Send = woDNetProtocolManager
						.get_SELECT_SIDE(WoD_Net_Protocol_ASCII.GameRoom.Select_Side_OPTION_GoodTeam);
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel()
						.sendMulticast(message_To_Send);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			
		case Composite_Options_Event.Event_Types.TEAM_PIRATES:
			try {
				byte[] message_To_Send = woDNetProtocolManager
						.get_SELECT_SIDE(WoD_Net_Protocol_ASCII.GameRoom.Select_Side_OPTION_PiratesTeam);
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel()
						.sendMulticast(message_To_Send);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		
		case Composite_Options_Event.Event_Types.READY_TO_PLAY:
			try {
				//woDP2PPeer.getMyScribeID()
				//recorrer usuarios, y comprobar si tengo setReady, 
				//si no lo tengo envio Ready_To_Go, si no Ready_To_Go_KO

				byte[] message_To_Send = null;

				
				for(WoD_Peer Peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
				{
					if(Peer.getScribeNode_ID().equals(woDP2PPeer.getMyScribeID()))
					{
						if (!Peer.isReadyToGo())
						{
							message_To_Send = woDNetProtocolManager
							.get_READY_TO_PLAY();
						}else
						{
							message_To_Send = woDNetProtocolManager
							.get_READY_TO_PLAY_KO();
						}
					}					 
				}
//				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().sendAnycast(
//						woDP2PPeer.getP2P_ROOT(), 
//						message_To_Send);
				
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().sendMulticast(message_To_Send);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;	
			
		case Composite_Options_Event.Event_Types.FORCE_START:
			try {
				int counter_Captain_team = 0;
				int i = 0;
				for (WoD_Peer woDServerClient : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
					if (woDServerClient.isReadyToGo())
					{
						i++;
					}
					if (woDServerClient.getROL() == WoD_Game.Game_Rols.Captain)
					{
						counter_Captain_team++;
					}
				}

				if(i== woDP2PPeer.getWoDClientPeersList().getWoD_Peers().size() && counter_Captain_team >= 1)
				{
					woDP2PPeer.send_Force_Start();
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case Composite_Options_Event.Event_Types.VOICE:
			
//			if ((!WoD_Voice.berrando()) && (WoD_Voice_Time.ceroOmenos())) WoD_Voice.berra();
//			else WoD_Voice.noBerres();
			if ((!WoD_Voice.berrando())) WoD_Voice.berra();
			else WoD_Voice.noBerres();
			break;
			
			
		case Composite_Options_Event.Event_Types.EXIT:
			woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().unsubscribe();
			node.destroy();
			
			break;

		default:
			break;
		}
		
	}
	
	
	
	@Override
	public void on_Composite_Chat_Changed(Composite_Chat_Event event) {
		
		switch (event.getEventType()) {
		case Composite_Chat_Event.Event_Types.SUBMIT:
			
			byte[] message_to_Send = null; 
			try {
				message_to_Send = woDNetProtocolManager.get_Chat_Message(
					compositeGameRoom.get_Composite_Chat().get_Text_Input_Chat().getText()
					);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}			
			woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().sendMulticast(message_to_Send);
			
			break;

		default:
			break;
		}
	}



	@Override
	public void on_WoD_P2P_Peer_Change(WoD_P2P_Peer_Event event) {
		switch (event.getEvent_Type()) {
		case WoD_P2P_Peer_Event.Event_Types.PEER_LIST_MODIFIED:
			
			System.out.println("Peer list modified");
			for (WoD_Peer woDPeer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
				System.out.println(woDPeer.getCliend_Id() + " " + woDPeer.getUserName());
			}
			
			compositeGameRoom.getPeerList_NEW().paint_Table(woDP2PPeer.getWoDClientPeersList().getWoD_Peers());
			
			manage_PEER_LIST_MODIFIED();
			
			start_Voice(woDP2PPeer.get_My_WoD_Peer(), woDP2PPeer.getWoDClientPeersList());
			break;

		case WoD_P2P_Peer_Event.Event_Types.PEER_TEAM_CHANGED:
			System.out.println("Peer team changed");
			
			ArrayList<WoD_Peer> woDPeers_captain_Team = new ArrayList<WoD_Peer>();
			ArrayList<WoD_Peer> woDPeers_pirates_Team = new ArrayList<WoD_Peer>();
			
			for (WoD_Peer woDPeer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
				if (woDPeer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
				{
					woDPeers_captain_Team.add(woDPeer);
				}
				else if (woDPeer.getTeam() == WoD_Game.Game_Teams.Pirates_Team)
				{
					woDPeers_pirates_Team.add(woDPeer);
				}
			}
			
			compositeGameRoom.getPlayerList_CaptainTeam().paint_Table(woDPeers_captain_Team);
			compositeGameRoom.getPlayerList_PiratesTeam().paint_Table(woDPeers_pirates_Team);
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_CAPTAIN_TEAM_FULL:

			System.out.println("Peer list modified");
			for (WoD_Peer woDPeer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
				System.out.println(woDPeer.getCliend_Id() + " " + woDPeer.getUserName());
			}

			//compositeGameRoom.getPeerList_NEW().paint_Table(woDP2PPeer.getWoDClientPeersList().getWoD_Peers());

			manage_CLIENT_SELECT_SIDE_INFO(event);

			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_CAPTAIN_TEAM_FREE:

			System.out.println("Peer list modified");
			for (WoD_Peer woDPeer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
				System.out.println(woDPeer.getCliend_Id() + " " + woDPeer.getUserName());
			}

			//compositeGameRoom.getPeerList_NEW().paint_Table(woDP2PPeer.getWoDClientPeersList().getWoD_Peers());

			manage_CLIENT_SELECT_SIDE_INFO(event);

			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_IS_ROOT:

			System.out.println("Peer is root");
			for (WoD_Peer woDPeer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers()) {
				System.out.println(woDPeer.getCliend_Id() + " " + woDPeer.getUserName());
			}

			Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
			optionsEvent.setEventType(Composite_Options_Event.Event_Types.USER_CAN_FORCE_START);						
			compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);
			
			ArrayList<String> maps = new ArrayList<String>();
//			maps.add("hola");
//			maps.add("hola2");
			
			File folder = new File("maps");
		    File[] listOfFiles = folder.listFiles();

		    for (int i = 0; i < listOfFiles.length; i++) {
		      if (listOfFiles[i].isFile()) {
		    	  if(listOfFiles[i].getName().contains(".xml"))
		    		  maps.add(listOfFiles[i].getName());
		      } else if (listOfFiles[i].isDirectory()) {
		        System.out.println("Directory " + listOfFiles[i].getName());
		      }
		    }
			
			compositeGameRoom.create_List_Maps().paint_Table(maps);
						
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_ISNT_ROOT:

			System.out.println("Peer isn't root");

			Composite_Options_Event optionsEvent2 = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
			optionsEvent2.setEventType(Composite_Options_Event.Event_Types.USER_CANT_FORCE_START);						
			compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent2);
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_CAN_SELECT_BOTH_ROLS:

			System.out.println("Peer isn't root");

			Composite_Rols_Event rolsEvent = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
			rolsEvent.setEventType(Composite_Rols_Event.Event_Types.ONLY_CAN_SELECT_BOTH);
			
			compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent);
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_ONLY_CAN_SELECT_CAPTAIN:

			System.out.println("Peer isn't root");

			Composite_Rols_Event rolsEvent1 = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
			rolsEvent1.setEventType(Composite_Rols_Event.Event_Types.ONLY_CAN_SELECT_CAPTAIN);
			
			compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent1);
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_ONLY_CAN_SELECT_MAIDEN:

			System.out.println("Peer isn't root");

			Composite_Rols_Event rolsEvent11 = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
			rolsEvent11.setEventType(Composite_Rols_Event.Event_Types.ONLY_CAN_SELECT_MAIDEN);
			
			compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent11);
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_PIRATE_CAN_SELECT_CAPTAIN:

			System.out.println("Peer isn't root");

			Composite_Options_Event optionsEvent3 = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
			optionsEvent3.setEventType(Composite_Options_Event.Event_Types.USER_CAN_SELECT_CAPTAIN);
			
			compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent3);
			
			
			break;
			
		case WoD_P2P_Peer_Event.Event_Types.PEER_CAN_SELECT_BOTH_TEAMS:

			System.out.println("Peer isn't root");

			Composite_Options_Event optionsEvent4 = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
			optionsEvent4.setEventType(Composite_Options_Event.Event_Types.USER_CAN_SELECT_BOTH);
			
			compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent4);
			
			
			break;
			
			
			
//		case WoD_P2P_Peer_Event.Event_Types.PEER_ONLY_CAN_SELECT_CAPTAIN:
//
//			System.out.println("Peer isn't root");
//
//			Composite_Rols_Event optionsEvent3 = new Composite_Rols_Event(compositeGameRoom.get_Composite_Options());
//			optionsEvent3.setEventType(Composite_Options_Event.Event_Types.ONLY_CAN_SELECT_CAPTAIN);						
//			compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent3);
//			
//			break;
			
			
		default:
			break;
		}
		
	}
	/**
	 * Shows error message
	 * @param error
	 */
	private void show_Error(String error)
	{
		MessageBox messageBox = new MessageBox(compositeGameRoom.getShell(), SWT.ICON_ERROR | SWT.OK);
		messageBox.setText("Error");
		messageBox.setMessage(error);
		messageBox.open();
	}
	

	/**
	 * Shows error message
	 * @param error
	 */
	private void show_Info(String information)
	{
		MessageBox messageBox = new MessageBox(compositeGameRoom.getShell(), SWT.ICON_INFORMATION | SWT.OK);
		messageBox.setText("Información");
		messageBox.setMessage(information);
		messageBox.open();
	}
	
	
	public void manage_PEER_LIST_MODIFIED()
	{
		if(woDP2PPeer.isIam_Root() && woDApplicationData.getMode() == WoD_Application_Data.Mode.WAN)
		{	
			byte[] message_to_Send = null; 
			try {
				message_to_Send = woDNetProtocolManager.get_Game_Id_Message(
					String.valueOf(woDApplicationData.getWoDGame().getID_Game() + "/" + woDApplicationData.getWoDGame().getGame_Title())
					);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel().sendMulticast(message_to_Send);					
			
			try {
				WoD_InfoPartidasActuales wipa = WoD_HttpMessage.GetCurrentPlayersOnGame(woDApplicationData.getWoDConfiguration().getWeb_Server(), woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), String.valueOf(woDApplicationData.getWoDGame().getID_Game()));
				
				if(Integer.parseInt(wipa.getPlayersNumber())-1<0)
				{
					ArrayList<String> PlayerNames = new ArrayList<String>();
					
					for (WoD_Peer Peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
					{
						PlayerNames.add(Peer.getUserName());
						System.out.println("\n PEER NAME: " + Peer.getUserName());
					}
					try {
						System.out.println("\n FROM WOD_GAME_MANAGER: ");
						WoD_HttpMessage.UpdateGame(woDApplicationData.getWoDConfiguration().getWeb_Server(), 
								woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
								woDApplicationData.getWoDPlayerData().getUserName(), 
								woDApplicationData.getWoDGame().getServerHost(), 
								String.valueOf(woDApplicationData.getWoDConfiguration().getControl_Port()), 
								"0", 
								String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
								woDApplicationData.getWoDGame().getGame_Title(), PlayerNames);
						
						System.out.println("\n woDAPP: -> GAMEID: " + String.valueOf(woDApplicationData.getWoDGame().getID_Game()));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						show_Error("HTTP Connection Error.");
					}
				}else
				{
					ArrayList<String> PlayerNames = new ArrayList<String>();
					for (WoD_Peer Peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
					{
						PlayerNames.add(Peer.getUserName());
						System.out.println("\n PEER NAME: " + Peer.getUserName());
					}
					try {
						WoD_HttpMessage.UpdateGame(woDApplicationData.getWoDConfiguration().getWeb_Server(), 
								woDApplicationData.getWoDConfiguration().getWeb_Server_Port(), 
								woDApplicationData.getWoDPlayerData().getUserName(), 
								woDApplicationData.getWoDGame().getServerHost(), 
								String.valueOf(woDApplicationData.getWoDGame().getServer_port()), 
								"1", String.valueOf(woDApplicationData.getWoDGame().getID_Game()), 
								woDApplicationData.getWoDGame().getGame_Title(), PlayerNames);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						show_Error("HTTP Connection Error.");
					//	e.printStackTrace();
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				show_Error("HTTP Connection Error.");
			}
			
		}
		
	}
	

	public void manage_CLIENT_SELECT_SIDE_OK(WoD_P2P_Control_Channel_Event event)
	{
		final WoD_ScribeContent woDScribeContent = (WoD_ScribeContent)event.getData();
		
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					String message_Received = woDNetProtocolManager.parse_SELECT_SIDE_OK(woDScribeContent.getMessage());
					//show_Error("SElect side OK. " + message_Received);
					
					if (message_Received.equalsIgnoreCase(WoD_Net_Protocol_ASCII.GameRoom.Select_Side_OPTION_GoodTeam))
					{						
						Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
						optionsEvent.setEventType(Composite_Options_Event.Event_Types.TEAM_CAPTAIN_OK);
						
						compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);
						
						int counter_Captain_Team = 0;
						for(WoD_Peer peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
						{
							if(peer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
							{
								counter_Captain_Team++;
							}
						}
						
						if(counter_Captain_Team == 1)
						{
							Composite_Rols_Event rolsEvent = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
							rolsEvent.setEventType(Composite_Rols_Event.Event_Types.ONLY_CAN_SELECT_CAPTAIN);
							
							compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent);
						}
						
						//compositeGameRoom.getDisplay().syncExec(runnable_event);
					}else if (message_Received.equalsIgnoreCase(WoD_Net_Protocol_ASCII.GameRoom.Select_Side_OPTION_PiratesTeam))
					{
						
						int counter_Captain_Team = 0;
						for(WoD_Peer peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
						{
							if(peer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
							{
								counter_Captain_Team++;
							}
						}
												
						Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
						optionsEvent.setEventType(Composite_Options_Event.Event_Types.TEAM_PIRATES_OK);						
						compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);
					}					
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		};		
		compositeGameRoom.getDisplay().asyncExec(runnable);			
		
	}
	
	public void manage_CLIENT_SELECT_SIDE_INFO(final WoD_P2P_Peer_Event event)
	{
		final WoD_ScribeContent woDScribeContent = (WoD_ScribeContent)event.getData();
		System.out.println("\nCLIENT SIDE INFO EVENT TYPE: " + String.valueOf(event.getEvent_Type()));
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					if (event.getEvent_Type() == WoD_P2P_Peer_Event.Event_Types.PEER_CAPTAIN_TEAM_FULL)
					{
						Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
						optionsEvent.setEventType(Composite_Options_Event.Event_Types.TEAM_CAPTAIN_FULL);						
						compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);						
						
					}else if(event.getEvent_Type() == WoD_P2P_Peer_Event.Event_Types.PEER_CAPTAIN_TEAM_FREE)
					{
						Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
						optionsEvent.setEventType(Composite_Options_Event.Event_Types.TEAM_CAPTAIN_FREE);
						
						compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);						
					}
					
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		};		
		compositeGameRoom.getDisplay().asyncExec(runnable);	
		
	}
	
	public void manage_CLIENT_SELECT_ROLE_OK(WoD_P2P_Control_Channel_Event event)
	{
		final WoD_ScribeContent woDScribeContent = (WoD_ScribeContent)event.getData();
		
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					String message_Received = woDNetProtocolManager.parse_SELECT_ROLE_OK(woDScribeContent.getMessage());
					//show_Error("SElect side OK. " + message_Received);
					
					if (message_Received.equalsIgnoreCase(WoD_Net_Protocol_ASCII.GameRoom.Select_Rol_OPTION_Captain))
					{	
						int counter_Captain_Team = 0;
						for(WoD_Peer peer : woDP2PPeer.getWoDClientPeersList().getWoD_Peers())
						{
							if(peer.getTeam() == WoD_Game.Game_Teams.Captain_Team)
							{
								counter_Captain_Team++;
							}
						}
						
						if(counter_Captain_Team == 1)
						{
							Composite_Rols_Event rolsEvent = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
							rolsEvent.setEventType(Composite_Rols_Event.Event_Types.ONLY_CAN_SELECT_CAPTAIN);
							
							compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent);
						}else
						{
							Composite_Rols_Event rolsEvent = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
							rolsEvent.setEventType(Composite_Rols_Event.Event_Types.SELECT_CAPTAIN_OK);
							
							compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent);
						}
						
						//compositeGameRoom.getDisplay().syncExec(runnable_event);
					}else if (message_Received.equalsIgnoreCase(WoD_Net_Protocol_ASCII.GameRoom.Select_Rol_OPTION_Maiden))
					{
						Composite_Rols_Event rolsEvent = new Composite_Rols_Event(compositeGameRoom.get_Composite_Rols());
						rolsEvent.setEventType(Composite_Rols_Event.Event_Types.SELECT_MAIDEN_OK);
						
						compositeGameRoom.get_Composite_Rols().fire_Composite_Rols_Event(rolsEvent);
					}					
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		};		
		compositeGameRoom.getDisplay().asyncExec(runnable);			
		
	}
	
	public void manage_CLIENT_JOIN_GAME_KO(WoD_P2P_Control_Channel_Event event)
	{
		final WoD_ScribeContent woDScribeContent = (WoD_ScribeContent)event.getData();
		
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					String message_Received = woDNetProtocolManager.parse_Join_Game_KO(woDScribeContent.getMessage());
					show_Error("Join Game KO. " + message_Received);
					
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		};
		compositeGameRoom.getDisplay().asyncExec(runnable);
		
		Runnable runnable_event = new Runnable() {
			
			@Override
			public void run() {
				Composite_Options_Event optionsEvent = new Composite_Options_Event(compositeGameRoom.get_Composite_Options());
				optionsEvent.setEventType(Composite_Options_Event.Event_Types.EXIT);
				
				compositeGameRoom.get_Composite_Options().fire_Composite_Options_Event(optionsEvent);
				
			}
		};
		

		compositeGameRoom.getDisplay().syncExec(runnable_event);
		
	}
	
	
	
	
	public void manage_CLIENT_SELECT_SIDE_KO(WoD_P2P_Control_Channel_Event event)
	{
		final WoD_ScribeContent woDScribeContent = (WoD_ScribeContent) event.getData();;
		
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				try {
					String message = woDNetProtocolManager.parse_SELECT_SIDE_KO(woDScribeContent
							.getMessage());
					show_Info("Select side KO " + message);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		};
		
		compositeGameRoom.getDisplay().asyncExec(runnable);		
		
		/**
		 * Throw close game evet
		 */
		WoD_Game_Manager_Event woDGameManagerEvent = new WoD_Game_Manager_Event(this);
		woDGameManagerEvent.setEvent_Type(WoD_Game_Manager_Event.Event_Type.Close_Game);
		notify_WoD_Game_Manager_Change(woDGameManagerEvent);
	}

	@Override
	public void on_Composite_Rols_Changed(Composite_Rols_Event event) {
		// TODO Auto-generated method stub
		switch (event.getEventType()) {

		case Composite_Rols_Event.Event_Types.SELECT_CAPTAIN:
			try {
				byte[] message_To_Send = woDNetProtocolManager
				.get_SELECT_ROL(WoD_Net_Protocol_ASCII.GameRoom.Select_Rol_OPTION_Captain);
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel()
				.sendMulticast(message_To_Send);
				System.out.println("WoD_Game_Manager: Sends Select_ROl");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		case Composite_Rols_Event.Event_Types.SELECT_MAIDEN:
			try {
				byte[] message_To_Send = woDNetProtocolManager
				.get_SELECT_ROL(WoD_Net_Protocol_ASCII.GameRoom.Select_Rol_OPTION_Maiden);
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel()
				.sendMulticast(message_To_Send);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	public void on_Composite_Maps_Changed(Composite_Maps_Event event) {
		// TODO Auto-generated method stub
		switch (event.getEventType()) {
		case Composite_Maps_Event.Event_Types.MAP_SELECTED:
			
			String selectedMap = compositeGameRoom.create_List_Maps().getSelectedMap();
				
			String e_string = selectedMap.replace("TableItem {", "");
			e_string = e_string.replace("}", "");
			
			System.out.println("SELECTED MAP: " + selectedMap);
			
			try {
				byte[] message_To_Send = woDNetProtocolManager
				.get_SELECT_MAP(selectedMap);
				woDP2PPeer.getWoDP2PControlChannel().getWoDScribeChannel()
				.sendMulticast(message_To_Send);
				System.out.println("WoD_Game_Manager: Sends Select_ROl");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
			
		default:
			break;
		}
	}
	
	
	/**
	 * This private method set and start voice module
	 */
	public void start_Voice(WoD_Peer woDPeer, WoD_Peers_List woDPeersList)
	{
		/**
		 * voice
		 */
		ArrayList<WoD_Peer> woDPeers_My_Team = new ArrayList<WoD_Peer>();
		for (WoD_Peer woDPeer_my_team : woDPeersList.getWoD_Peers()) {
			if (woDPeer_my_team.getTeam() == woDPeer.getTeam())
			{
				woDPeers_My_Team.add(woDPeer_my_team);
			}
		}
		
		wod_Voice  = new WoD_Voice(woDPeers_My_Team);
		wod_Voice.setIn_port(woDPeer.getVoice_UDP_Port());
		
		wod_Voice.startTest(true);
		
		
		Runnable runnable = new Runnable() {
			
			@Override
			public void run() {
				while (woDApplicationData.getWoDGame().getGame_State() == WoD_Game.Game_States.Game_Room) {
					try {
						Thread.currentThread();
						Thread.sleep(40);
						if (!WoD_Voice_Time.ceroOmenos()) WoD_Voice_Time.decrementa(40);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
			}
		};
		
		Thread thread = new Thread(runnable);
		thread.setDaemon(true);
//		thread.start();
		
		
	}
	

}
